package com.yy.QSManage.api;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.yy.QSManage.common.Result;
import com.yy.QSManage.model.dto.EnumItemDto;
import com.yy.QSManage.model.entity.FaSysDataSource;
import com.yy.QSManage.model.entity.FaSysEnum;
import com.yy.QSManage.model.entity.FaSysGen;
import com.yy.QSManage.model.validatio.Create;
import com.yy.QSManage.service.FaSysDataSourceService;
import com.yy.QSManage.service.FaSysEnumService;
import com.yy.QSManage.service.FaSysGenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/FaSysDataSourceApi")
@Api(tags = "数据源")
public class FaSysDataSourceApi extends BaseApi<FaSysDataSource>{

    @Autowired
    FaSysGenService genService;

    @Autowired
    FaSysDataSourceService dataSourceService;

    @Autowired
    FaSysEnumService enumService;

    @Override
    public Result<Boolean> add(@RequestBody @Validated(Create.class) FaSysDataSource query) {
        String source = query.getSource();
        if(query.getType().equals("table") || query.getType().equals("view") ){
            // 新增代码生成记录
            FaSysGen faSysGen = new FaSysGen();
            String entityName = StrUtil.toCamelCase(source);
            entityName = StrUtil.upperFirst(entityName);
            String id = IdUtil.fastSimpleUUID();
            faSysGen.setId(id);
            faSysGen.setEntityName(entityName);
            genService.save(faSysGen);
            query.setGenId(id);
        }else if (query.getType().equals("enum")) {
            // 判断枚举code是否存在
            enumService.ifExist(FaSysEnum::getCode, source, "该枚举数据源已存在 "+source);
            // 添加默认空值
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(new JSONObject(new EnumItemDto()));
            FaSysEnum saveEnum = new FaSysEnum();
            saveEnum.setCode(source)
                    .setName(query.getName())
                    .setDataJson(jsonArray.toString());
            enumService.save(saveEnum);
        }
        return super.add(query);
    }

    @ApiOperation("获取所有表")
    @GetMapping("/tables")
    public Result<List<String>> tables(){
        return Result.success(dataSourceService.tables());
    }
}
